package com.iscas.imchat.sso;

import com.google.gson.Gson;
import com.iscas.imchat.utils.Util;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Author: zhd
 * Data: 2022/5/27
 */

public class RegServerHandler extends SimpleChannelInboundHandler<String> {

    private Util util;

    public RegServerHandler(Util databaseUtility) {
        this.util = databaseUtility;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 获取当前channel
        Channel channel = ctx.channel();

        // Read class
        Gson gson = new Gson();
        RegReqMessage message = gson.fromJson(msg,RegReqMessage.class);

        // 验证是否为注册信息
        if(message.getRequestType() == 1){
            System.out.println("接收到注册消息");
            // 随机生成uid
            String uid = null;
            while(uidExists(uid)){
                uid = uidGenerator(uid);
            }
            // 写账号密码进入数据库
            createAccount(uid,message.getNickname(),message.getPassword());
            System.out.println("uid，用户名，密码： " + message.getNickname()+" "+ message.getPassword());
            // 返回uid
            RegReqMessage returnMsg = new RegReqMessage();
            returnMsg.setRequestType(2);    //返回消息置2
            returnMsg.setUid(uid);      //uid
            String output = new Gson().toJson(returnMsg);
            // 当前channel返回信息
            channel.writeAndFlush(output);
        }
        else{
            System.out.println("注册消息不合法");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    /**
     * 生成uid
     * @param uid 初始uid，期望输入为空
     * @return uid
     */
    // 最低6位，重复号码则向后添加一位
    private String uidGenerator(String uid){
        // uid为空或者满位仍重复则生成随机6位
        if(uid == null || uid.length() == 12){
            // 第一位1-9随机
            uid = String.valueOf(new Random().nextInt(9) + 1);
            // 2-6位0-9随机
            int i = 0;
            StringBuilder uidBuilder = new StringBuilder(uid);
            while(i < 5){
                uidBuilder.append(new Random().nextInt(10));
                i++;
            }
            uid = uidBuilder.toString();
            return uid;
        }
        //添加1位
        else{
            return uid += String.valueOf(new Random().nextInt(10));
        }
    }

    private boolean uidExists(String uid){
        if (uid == null) return true;
        List<HashMap<String, Object>> userList = this.util.Select("select * from account where uid='" + uid + "';");
        return userList.size() != 0;
    }

    private void createAccount(String uid, String nickname, String password){
        util.Insert("insert into account (uid, nickname, password) values ('"+uid+"', '"+nickname+"', '"+password+"');");
    }
}
